using Microsoft.AspNetCore.SignalR;
using OrderingSystem.API.Hubs;
using OrderingSystem.Core.Interfaces;
using OrderingSystem.Core.Entities;

namespace OrderingSystem.API.Services
{
    public class NotificationService : INotificationService
    {
        private readonly IHubContext<NotificationHub> _hubContext;

        public NotificationService(IHubContext<NotificationHub> hubContext)
        {
            _hubContext = hubContext;
        }

        public async Task SendOrderStatusChangedAsync(Order order)
        {
            var message = new
            {
                orderId = order.id,
                orderNumber = order.dingdanbianhao,
                status = order.ispay,
                timestamp = DateTime.Now
            };

            await _hubContext.Clients.All.SendAsync("OrderStatusChanged", message);
        }

        public async Task SendNewOrderAsync(Order order)
        {
            decimal totalAmount = GetTotalAmount(order.zongjine);

            var message = new
            {
                orderId = order.id,
                orderNumber = order.dingdanbianhao,
                items = order.caipinmingcheng,
                totalAmount = totalAmount,
                createdAt = order.addtime,
                timestamp = DateTime.Now
            };

            await _hubContext.Clients.All.SendAsync("NewOrder", message);
        }

        public async Task SendOrderCancelledAsync(Order order)
        {
            var message = new
            {
                orderId = order.id,
                orderNumber = order.dingdanbianhao,
                timestamp = DateTime.Now
            };

            await _hubContext.Clients.All.SendAsync("OrderCancelled", message);
        }

        public async Task SendSystemNotificationAsync(string message, string role = null)
        {
            if (string.IsNullOrEmpty(role))
            {
                await _hubContext.Clients.All.SendAsync("SystemNotification", new { message, timestamp = DateTime.Now });
            }
            else
            {
                await _hubContext.Clients.Group(role).SendAsync("SystemNotification", new { message, timestamp = DateTime.Now });
            }
        }

        private static decimal GetTotalAmount(string zongjine)
        {
            if (decimal.TryParse(zongjine, out var amount))
            {
                return amount;
            }
            return 0;
        }
    }
} 